package com.fuhe.studydemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;

public class RefreshActivity extends Activity {

    private LinearLayout header;
    private Button button_refresh;
    private boolean isStarted = false;
    private int mOffset = 0;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refresh);

        initView();
    }

    private void initView() {
        header = findViewById(R.id.header);
        button_refresh = findViewById(R.id.button_refresh);
    }

    public void doRefresh(View view) {
        int realHeight = getRealHeight(header);
        if (!isStarted) {
            mOffset = -realHeight;
            button_refresh.setEnabled(false);
            mHandler.post(mRefresh);
        } else {
            button_refresh.setText("开始刷新");
            header.setVisibility(View.GONE);
        }
        isStarted = !isStarted;
    }

    private Runnable mRefresh = new Runnable() {
        @Override
        public void run() {
            if (mOffset<=0){
                header.setPadding(0,mOffset,0,0);
                header.setVisibility(View.VISIBLE);
                mOffset+=8;
                mHandler.postDelayed(this,10);
            }else {
                button_refresh.setText("恢复页面");
                button_refresh.setEnabled(true);
            }
        }
    };

    private int getRealHeight(LinearLayout header) {
        //获得布局参数
        ViewGroup.LayoutParams layoutParams = header.getLayoutParams();

        //如果没有使用默认参数
        if (layoutParams == null) {
            layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        //计算宽度
        int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, layoutParams.width);
        int heightSpec;

        //计算高度
        //当height>0时,为确切值
        if (layoutParams.height > 0) {
            heightSpec = View.MeasureSpec.makeMeasureSpec(layoutParams.height, View.MeasureSpec.EXACTLY);
        } else//否则,为不确定值
        {
            heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        }
        //根据计算结果重新丈量
        header.measure(widthSpec, heightSpec);

        return header.getMeasuredHeight();
    }


}
